<template>
  <div>
    <div v-if="!isShowPage" style="margin-top: 20px">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :span="2"><el-form-item label="搜索"> </el-form-item></el-col>
          <el-col :span="6">
            <el-form-item label="关键词" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入课文名称"
                clearable
                @keyup.enter.native="keywordSearch"
                title="课文名称,课文ID,作者名称,名师诵读"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="keywordSearch"
              >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="2"><el-form-item label="筛选"> </el-form-item></el-col>
          <el-col :span="6"
          ><el-form-item label=" 归属年级" prop="gradeId">
            <el-select v-model="queryParams.gradeId" placeholder="请选择" @change="selectGrade">
              <el-option
                v-for="item in gradeList"
                :key="item.gradeId"
                :label="item.gradeName"
                :value="item.gradeId"
              >
              </el-option>
            </el-select>
          </el-form-item></el-col
          >
          <el-col :span="6">
            <el-form-item label="归属学期" prop="semesterName">
              <el-select v-model="queryParams.semesterId" placeholder="请选择" @click="semesterList">
                <el-option
                  v-for="item in semesterList"
                  :key="item.semesterId"
                  :label="item.semesterName"
                  :value="item.semesterId"
                >
                </el-option>
              </el-select>
            </el-form-item></el-col
          >
          <el-col :span="6"
          ><el-form-item label="归属单元" prop="unitId">
            <el-select v-model="queryParams.unitId" placeholder="请选择" @change="selectUnit">
              <el-option
                v-for="item in unitList"
                :key="item.unitId"
                :label="item.unitName"
                :value="item.unitId"
              >
              </el-option>
            </el-select>
          </el-form-item></el-col
          >
        </el-row>
      </el-form>
       <!-- @selection-change="handleSelectionChange" -->
      <el-table
        v-loading="loading"
        :data="recommendList"
      >
        <el-table-column label="作品ID" align="center" prop="recommendId" />
        <el-table-column label="课文名称" align="center" prop="textName" />
        <el-table-column label="作者名称" align="center" prop="textAuthor" />
        <el-table-column label="归属年级" align="center" prop="gradeName" />
        <el-table-column label="归属单元" align="center" prop="unitName" />
        <el-table-column label="朗读者" align="center" prop="userName" />
        <el-table-column label="当前热度" align="center" prop="hot" />
        <el-table-column label="热度排名" align="center" prop="hotRanking" />
        <el-table-column
          label="信息更新时间"
          align="center"
          prop="updatedTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updatedTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['recitation:text:edit']"
              >查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['recitation:text:edit']"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 @size-change="handleSizeChange" -->
    <el-pagination
      v-show="!isShowPage"
      style="margin-top: 20px"
      align="center"
      @current-change="getRecommendList"
      @size-change="handleSizeChange"
      background
      prev-text="上一页"
      next-text="下一页"
      :current-page="page"
      :page-sizes="[10,20,30,40,50]"
      :page-size="limit"
      :pager-count="5"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>

    <!-- 点击查看后的页面 -->
    <div v-show="isShowPage" style=" margin-top:20px; width: 500px;">
      <el-form
        :model="form"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="作品ID" prop="recommendId">
          <span>{{ form.recommendId }}</span>
        </el-form-item>
        <el-form-item label="课文名称" prop="textName">
          <span>{{ form.textName }}</span>
        </el-form-item>
        <el-form-item label="作者名称" prop="textAuthor">
          <span>{{ form.textAuthor }}</span>
        </el-form-item>
        <el-form-item label="归属年级" prop="gradeName">
          <span>{{ form.gradeName }}</span>
        </el-form-item>
        <el-form-item label="归属单元" prop="unitName">
          <span>{{ form.unitName }}</span>
        </el-form-item>
        <el-form-item label="朗读者" prop="userName">
          <span>{{ form.userName }}</span>
        </el-form-item>
        <el-form-item label="当前热度" prop="hot" name="hot">
          <span v-show="isShowHotSpan">{{ form.hot }}</span>
          <el-button
            v-show="isShowHotSpan"
            icon="el-icon-edit"
            size="medium"
            style="border: none"
            @click="toInput"
            name="hot"
          ></el-button>
          <el-input
            v-show="isShowHotIput"
            v-model="form.hot"
            placeholder="请输入"
            clearable
            :style="{ width: '20%' }"
            @keyup.enter.native="toSpan"
            @blur="toSpan"
            name="hotInput"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="热度排名" prop="hotRanking">
          <span v-show="isShowHotRankingSpan">{{ form.hotRanking }}</span>
          <el-button
            v-show="isShowHotRankingSpan"
            icon="el-icon-edit"
            size="medium"
            style="border: none"
            @click="toInput"
          ></el-button>
          <el-input
            v-show="isShowHotRankingIput"
            v-model="form.hotRanking"
            placeholder="请输入"
            clearable
            :style="{ width: '20%' }"
            @keyup.enter.native="toSpan"
            @blur="toSpan"
            name="hotRankingInput"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="音频播放" prop="ftextIle">
          <audio-player :url="audioFile" ref="audioPlayer"></audio-player>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  listRecommend,
  getRecommend,
  updateRecommend,
  delRecommend,
} from "@/api/ywjy/recommend";
import {listGrade} from "@/api/ywjy/grade";
import {listSemester} from "@/api/ywjy/semester";
import {listUnit} from "@/api/ywjy/unit";
import AudioPlayer from "@/components/AudioPlayer";
import { getSubjectList } from '@/api/ywjy/text'
export default {
  name: "RecommendList",
  data() {
    return {
      recommendList: [], // 推荐作品表格数据
      total: 0, // 分页需要的数据
      limit: 1, //分页需要的数据
      page: 1, //分页需要的数据
      loading: true, // 遮罩层
      isShowAdd: false, // 是否显示查看后的页面
      gradeList: [], // 年级表格数据
      unitList: [], //归属表格数据
      isShowPage: false, //查看页面 初始化不展示,
      gradeValue: "", //搜索框年级
      unitValue: "", //搜索框单元
      isSpan: true, //当前span按钮显示,如果为false input框显示
      semesterValue:"",
      semesterList:[],
      //以上是我写的有用的数据 以下不是我写的 待整理的数据
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      open: false, //dialog框默认是关闭的
      title: "", // 弹出层标题
      subjectList:[],// 获取题材列表
      // 查询参数
      queryParams: {
        pageNum: 1, //调作品列表接口需要携带的参数
        pageSize: 10, //调作品列表接口需要携带的参数
        userName: null, //调作品列表接口需要携带的参数
        srot: null, //调作品列表接口需要携带的参数
        gradeId: null, //调作品列表接口需要携带的参数
        unitName: null, //调作品列表接口需要携带的参数
        unitId: null,
        semesterId:"",
        //以上是我写的有用的数据 以下不是我写的 待整理的数据

        famousTeacherId: null,
        teacherName: null,
        ftextIle: null,
        contentId: null,
        semester: null,
        createdBy: null,
        deleteFlag: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
      },
      // 表单参数 验证的参数 点击添加按钮需要收集的数据
      form: {
        recommendId: "", //作品ID
        textName: "", //课文名称
        textAuthor: "", //课文作者
        gradeName: "", //归属年级
        userName: "", //朗读者
        hot: "", //当前热度
        hotRanking: "", //热度排名
        ftextIle: "", //音频文件url
      },
      //表单验证
      rules: {
        hot: [
          {
            required: true,
            message: "请输入数字且大于1",
            trigger: "blur",
            pattern: /^\d+$/,
          },
        ],
         hotRanking: [
          {
            required: true,
            message: "请输入数字且大于1",
            trigger: "blur",
            pattern: /^\d+$/,
          },
        ],
      },
      isShowHotSpan:true,//默认显示热度span
      isShowHotIput:false,//默认不显示热度input
      isShowHotRankingSpan:true,//默认显示热度排名span
      isShowHotRankingIput:false,//默认不显示热度排名input
      audioStatus:require("../../../assets/icons/start.png"),//播放
      audioIconPause:require("../../../assets/icons/pause.png"),//暂停
      audioIconCircle:require("../../../assets/icons/circle.png"),//播放进度圆点
      audioProgressPercentage:0,//播放进度百分比
      audioFile:require("../../../assets/audio/demo.mp3"),//默认mp3文件
      audioInterval:"",//播放定时器,定时获得播放进度
      audioIconCircleOffsetLeft:0,//用来存初始时候的进度按钮的左坐标
      yuandianchushiweizhi:-1,//游标初始位置.写成-1是为了判断是否为初始值时方便.
    };
  },
  components:{
    AudioPlayer
  },
  created() {
    this.getRecommendList();
    this.getGrade()
    this.getSubject()
  },
  methods: {
    // 查询课文列表
    getRecommendList(pager = 1) {
      this.page = pager;
      this.loading = true;
      listRecommend(this.queryParams).then((response) => {
        //this.recommendList = response.rows;
        this.recommendList = response.rows.splice(this.limit*(this.page-1),this.limit*this.page);
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取年级列表
    getGrade() {
      this.loading = true;
      listGrade(this.queryParams).then((response) => {
        this.gradeList = response.rows
        this.loading = false;
      });
    },
    //选择grade的id获取学期信息
    selectGrade() {
      this.reset()
      listSemester(this.queryParams).then((res) => {
        this.loading = true;
        this.semesterList = res.rows;
        this.loading = false;
        this.getRecommendList()
      });
    },
    //选择学期时,年级的id和学期id获取单元信息
    selectSemester() {
      this.reset()
      this.loading = true
      listUnit(this.queryParams).then((res) => {
        //console.log("7777777777777",res.rows)
        this.unitList = res.rows
      })
      this.loading = false
      this.getRecommendList()
    },
    //重置按钮
    resetQuery() {
      this.queryParams.textName = "";
      this.queryParams.semesterId=""
      this.resetForm("queryForm");
      this.getRecommendList();
      this.getGrade()
    },
    //选择单元时
    selectUnit() {
      this.queryParams.pageNum = 1;
      this.reset()
      this.getRecommendList()
    },
    //获取题材列表
    getSubject() {
      this.loading = true;
      getSubjectList(this.queryParams).then((response) => {
        this.subjectList = response.rows;
       // console.log("55555555555555555",subjectList)
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        textId: null,
        textName: null,
        textAuthor: null,
        gradeId: null,
        unitId: null,
        famousTeacherId: null,
        teacherName: null,
        ftextIle: null,
        contentId: null,
        semesterId:"",
        semester: null,
        createdBy: null,
        deleteFlag: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        content: "", //课文全文朗读文本内容
        paragraphs: [
          {},
          {
            paragraphName: "",
            paragraph: "",
            ftextIle: "",
            contentText: "",
          },
        ], //段落数组
        type: "", //归属题材
      };
      this.resetForm("form");
      this.type = "";
      this.count = [1];
      this.gradeList = [], // 年级表格数据
        this.unitList = [], //归属表格数据
        this.semesterList = [] //归属学期数据

      //console.log("this.form",this.form)
    },
    //当点击查看页面 当前热度后面的小笔按钮时 触发的回调 从span状态切换成input框输入状态
    toInput(event) {
      let name=""
      if(event.target.className=="el-icon-edit"){//判断点的是"小笔"还是button?
        //console.log('666',event.target.parentNode.name)
        name=event.target.parentNode.name
      }else {
        //console.log('777',event.target.name)
        name=event.target.name
      }
      //console.log("name",name)
      if (name=="hot"){//判断点击的是不是"当前热度"
        this.isShowHotSpan=false;this.isShowHotIput=true;
      }else{//点击的是"热度排名"
        this.isShowHotRankingSpan=false;this.isShowHotRankingIput=true
      }
    },
    //input框输入内容时 按下回车键或者失去焦点时 从input框变成span
    toSpan(event) {
      let name=""
      //console.log('777',event.target.name)
      name=event.target.name
      //console.log(name)
      if (name=="hotInput"){
        this.isShowHotIput=false;this.isShowHotSpan=true;
        //console.log("这是hotInput")
      }
      if(name=="hotRankingInput"){
        this.isShowHotRankingIput=false;this.isShowHotRankingSpan=true;
        //console.log("这是hotRankingInput")
      }
    },
    // 表单重置

    //点击查看按钮
    handleUpdate(row) {
      this.isShowPage = true; //打开查看页面
      this.reset();
      const recommendId = row.recommendId || this.ids;
      getRecommend(recommendId).then((response) => {
        this.form = response;
        this.open = true;
        this.title = "查看";
      });
    },
    //查看页面的取消按钮 点击时 返回详情页
    cancel() {
      this.isShowPage = false;
      this.$refs.audioPlayer.stop();
    },
    //关键字后面的搜索按钮操作
    keywordSearch(){
      this.queryParams.pageNum = 1;
      this.getRecommendList();
    },
    //归属学期后面的搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getRecommendList();
    },

    //保存按钮 */
    submitForm() {
          if (this.form.recommendId != null) {
            updateRecommend(this.form).then((response) => {
              this.msgSuccess("保存成功");
              this.open = false;
              this.getRecommendList();
            });
          }
    },
    //删除按钮操作
    handleDelete(row) {
        const recommendId = row.recommendId || this.ids;
        this.$confirm(
          `删除 ${recommendId}作品后APP上将不再展示该作品,确定要删除吗?`,
          {
            center: true,
            customClass: "deleteConfirm",
            cancelButtonText: "取消",
            confirmButtonText: "确定",
          }
        )
          .then(function () {
            return delRecommend(recommendId);
          })
          .then(() => {
            this.msgSuccess("删除成功");
            //删除成功后 看当前页面有几个 如果比1大 就停留在当前页,如果只有一个 就去上一页
            this.getRecommendList(
              this.recommendList.length > 1 ? this.page : this.page - 1
            );
          })
          .catch(() => {});
    },

    changeAudioStatus(){
      //切换音频播放按钮图标的操作
      //https://gitee.com/xdql/vue-audio-player 音频播放api
      let sToM=function (s){//把秒变成分钟
        console.log("当前秒是:",s)
        let minute=Math.floor(s/60)//取计算结果的整数部分
        if (minute<10){
          minute="0"+minute
        }
        console.log("播放分钟是:",minute)
        let second=Math.floor(s%60)//取计算结果的整数部分
        if (second<10){
          second="0"+second
        }
        console.log("播放秒是:",second)
        let result=minute+":"+second;
        return result
      }
      //event.stopPropagation();//防止冒泡
      let audioObj=document.getElementById("audio")//获得音频dom对象
      //let audioInterval
      console.log("播放状态:",audioObj.paused)
      let vc=this//把this承接到window中来,在播放到终点时,为播放按钮更改图标时,需要修改this.audioStatus
      if (audioObj.paused){
        //console.log("要开")
        this.audioStatus=require("../../../assets/icons/pause.png")//准备好暂止按钮

        //获取播放比例
        console.log("播放比例",audioObj.currentTime/audioObj.duration*100+"%")
        let bofangbili=audioObj.currentTime/audioObj.duration

        console.log("查看播放器有哪些方法,有没有重播方法?",audioObj)
        console.dir(audioObj)
        if(bofangbili>=0.99){//这就是播放完了,希望重新播放
          //需要重置播放进度为0或重新加载音频
          audioObj.currentTime=0
          //audioObj.load()
          bofangbili=audioObj.currentTime/audioObj.duration//重新计算播放比例
          console.log("查看播放比例是否已经重置:",bofangbili)
          return;
          audioObj.play()//重置之后再播放
        }else {//播放百分比是0或半截,就是继续播放
          audioObj.play()
        }
        let n=0//是定时器循环的次数,为了看日志方便,我让他循环2次,就结束
        let audioIconCircleObj=document.getElementById("audioIconCircle")//获取游标
        if(vc.yuandianchushiweizhi==-1){//当游标位置为-1时,表名是第一次开始播放.这时候,要获取一下游标的初始位置;以后每次"继续播放"时,都不再获得游标的初始位置.
          // 这样就为继续播放时 定位初始位置+播放百分比*外部div宽度 取到一个可预期的浮动范围
          vc.yuandianchushiweizhi=audioIconCircleObj.offsetLeft
        }

      }else{
        audioObj.pause()
        //console.log("要停")
        //console.log("click事件中的this是vc:",this)
        vc.audioStatus=require("../../../assets/icons/start.png")//把开始按钮预备好
        clearInterval(vc.audioInterval)
        return
      }
    },
    handleSizeChange(size){
      this.limit=size
      this.getRecommendList()
    }
  },
};


class myTimer{//定时器类
  /* cb回调函数
  /* sec执行间隔
  * */
  constructor(cb,sec) {
    this.cb=cb;
    this.timer=null;
    this.sec=sec;
  }
  run(){
    this.timer=setInterval(this.cb,this.sec);
  }
  stop(){
    clearInterval(this.timer);
    this.timer=null
  }
}
</script>
<style  scoped>
</style>
